<template>
  <!-- 好生活资金池 -->
  <div class="efCapitalSummary" ref="outBox">
    <searchForm :typeForm="model" @searchList="searchList(1)" @exportList="exportList"></searchForm>
    <div class="fixedBox">
      <top-btn :activeBtn="thisOutProp" :btns="tableTitleInfos.slice(4)" @btnsClick="jumpFlag"></top-btn>
      <el-table
        border
        stripe
        :data="tableData"
        style="width: 100%"
        ref="table"
        :max-height="tableHeight"
        @selection-change="selectChange"
      >
        <el-table-column
          :selectable="selectable"
          type="selection"
          align="center"
          :fixed="true"
          width="50"
        ></el-table-column>
        <el-table-column
          type="index"
          align="center"
          label="序号"
          width="50"
          :fixed="true"
          :index="indexFun"
        ></el-table-column>

        <el-table-column
          :prop="out.prop"
          v-for="(out,idx) in tableTitleInfos"
          :key="idx"
          align="center"
          :width="idx<4?100:out.prop == 'packageName'?200:''"
          :fixed="idx<4"
          :show-overflow-tooltip="true"
        >
          <!-- idx<4  4为4个表格固定列 每列宽度为100  在锚点定位中会加上 -->
          <template slot="header" slot-scope="scope">
            <p :key="scope.$index" style="width:100%;margin:0;" :ref="'out'+out.prop">{{out.label}}</p>
          </template>
          <template slot-scope="scope">
            <span v-if="scope.$index == 0">{{formMoneyValue(scope.row[out.prop])}}</span>
            <span
              v-else-if="out.prop == 'packageName' && scope.row[out.prop]"
              class="break-text"
              @click="viewCommInfo(scope.row.customerFollowId|| '')"
            >{{scope.row[out.prop] }}</span>

            <span v-else>{{tableFormatter(out.prop,scope.row[out.prop]) || "——"}}</span>
          </template>
          <el-table-column
            :prop="prop"
            v-for="({label,prop,location},k) in out.child ||[]"
            :key="k"
            align="center"
            :label="label"
            :min-width="150"
          >
            <template slot-scope="scope">
              <span
                v-if="Array.isArray(scope.row[prop]) && (idx === 8 || idx === 9  || idx === 10)"
              >{{renderCommArray(scope.row,prop,location,scope.$index)}}</span>
              <span v-else-if="scope.$index == 0">{{formMoneyValue(scope.row[prop]) || "——"}}</span>
              <span v-else>{{tableFormatter(prop,scope.row[prop]) || "——" }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column prop="province" align="center" label="操作">
          <template slot-scope="scope">
            <el-button v-if="scope.$index" @click="viewList(scope.$index)" type="text">查看详情</el-button>
            <span v-else>——</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top:30px"
        :current-page.sync="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="totalSize"
      ></el-pagination>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import api from "@/api/apiPath";
import searchForm from "./searchForm";
import utils from "@/common/utils.js";
import topBtn from "./navBtnsBar";
export default {
  name: "efCapitalSummary",
  title: '好生活资金池',
  components: {
    searchForm,
    topBtn
  },
  data() {
    return {
      model: {
        companyName: "",
        cityId: "",
        projectId: "",
        devId: "",
        buildId: "",
        unit: "",
        floor: "",
        brokerType: "",
        cellId: "",
        customer: "",
        beginTime: "",
        endTime: "",
        purchaseTimeBeginTime: "",
        purchaseTimeEndTime: "", //认购时间
        signTimeBeginTime: "",
        signTimeEndTime: "", //签约时间
        purchaseCreateTimeBeginTime: "",
        purchaseCreateTimeEndTime: "" //提交时间
      },
      pageNum: 1,
      pageSize: 10, //每页几条
      totalSize: 0,
      thisOutProp: "name1",
      tableData: [],
      tableTitleInfos: [
        { label: "楼盘名称", prop: "devName" },
        { label: "业绩归属", prop: "brokerType" },
        { label: "房间号", prop: "cellName" },
        { label: "跟进状态", prop: "followName" },
        {
          label: "客户基本资料",
          prop: "name1",
          child: [
            { label: "开发商", prop: "companyName" },
            { label: "城市", prop: "city" },
            { label: "项目名称", prop: "projectName" },
            { label: "合同面积（m²）", prop: "houseArea" },
            { label: "合同总价（元）", prop: "actualPayment" },
            { label: "客户姓名", prop: "customerName" },
            { label: "手机号", prop: "customerPhone" },
            { label: "提交时间", prop: "purchaseCreateTime" },
            { label: "认购时间", prop: "purchaseTime" },
            { label: "草签时间", prop: "initialTime" },
            { label: "签约时间", prop: "signTime" }
          ]
        },
        {
          label: "收入基本状态",
          prop: "name2",
          child: [
            { label: "前佣预收入（元）", prop: "frontBrokerageTotalPre" },
            { label: "应收前佣（元）", prop: "frontBrokerageTotal" },
            { label: "已收前佣（元）", prop: "orderPaid" },
            { label: "收款时间", prop: "orderPaidTime" },
            { label: "后佣预收入（元）", prop: "backBrokerageTotalPre" },
            { label: "应收后佣（元）", prop: "backBrokerageTotal" },
            { label: "已收后佣（元）", prop: "paymentsReceived" },
            { label: "收款时间", prop: "paymentsReceivedTime" },
            { label: "经纪人奖励预收", prop: "awardsAmountPre" },
            { label: "应收经纪人奖励（元）", prop: "awardsAmount" },
            { label: "已收经纪人奖励（元）", prop: "awardsAmountPaid" },
            { label: "收款时间", prop: "awardsAmountPaidTime" }
          ]
        },
        {
          label: "收入汇总",
          prop: "name3",
          child: [
            { label: "预收入汇总（元）", prop: "brokerageTotalPre" },
            { label: "应收汇总（元）", prop: "brokerageTotal" },
            { label: "已收汇总（元）", prop: "brokeragePaidTotal" }
          ]
        },
        {
          label: "外部结佣明细",
          prop: "name4",
          child: [
            { label: "经纪公司", prop: "brokerCompanyName" },
            { label: "经纪人", prop: "brokerName" },
            { label: "现场销售", prop: "salesperson" }
          ]
        },
        {
          label: "前佣佣金情况",
          prop: "name5",
          child: []
        },
        {
          label: "后佣佣金情况",
          prop: "name6",
          child: []
        },
        {
          label: "经纪人奖励佣金情况",
          prop: "name7",
          child: []
        },
        {
          label: "泛营销老带新",
          prop: "name8",
          child: [
            {
              label: "好生活泛营销佣金（元）",
              prop: "easylifeMarketingAmount"
            },
            { label: "网络推客佣金（元）", prop: "pusherTotalAmount" }
          ]
        },
        {
          label: "好生活平台费",
          prop: "name9",
          child: [
            { label: "前佣平台费应收（元）", prop: "easyLifeFrontAmount" },
            { label: "前佣平台费已收（元）", prop: "easyLifeFrontAmountPaid" },
            { label: "后佣平台费应收（元）", prop: "easyLifeAfterAmount" },
            { label: "后佣平台费已收（元）", prop: "easyLifeAfterAmountPaid" },
            {
              label: "经纪人奖励平台费应收（元）",
              prop: "easyLifeAwardsAmount"
            },
            {
              label: "经纪人奖励平台费已收（元）",
              prop: "easyLifeAwardsAmountPaid"
            }
          ]
        },
        {
          label: "开发商返回款",
          prop: "name10",
          child: [
            { label: "前佣返还款（元）", prop: "developerFrontBrokerage" },
            { label: "前佣实际返还（元）", prop: "developerFrontActBrokerage" },
            { label: "后佣返还款（元）", prop: "developerAfterBrokerage" },
            {
              label: "后佣应收实际返还（元）",
              prop: "developerAfterActBrokerage"
            },
            { label: "经纪人奖励应收（元）", prop: "developerAwardsAmount" },
            {
              label: "经纪人奖励实际返还（元）",
              prop: "developerAwardsActAmount"
            }
          ]
        },
        { label: "佣金套餐", prop: "packageName" }
      ],
      tableHeight: 0
    };
  },
  created() {
    this.searchList();
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = this.$refs.outBox.scrollHeight - 160;
    });
  },
  activated(){
    this.searchList();
    this.$nextTick(() => {
        this.tableHeight = this.$refs.outBox.scrollHeight - 160;
    });
  },
  methods: {
    tableFormatter(prop, val) {
      let moneyFormatter = [
        "actualPayment",
        "frontBrokerageTotal",
        "orderPaid",
        "backBrokerageTotal",
        "paymentsReceived",
        "awardsAmount",
        "awardsAmountPaid",
        "brokerageTotal",
        "brokeragePaidTotal",
        "brokerFrontAmount",
        "brokerFrontAmountPaid",
        "brokerAfterAmount",
        "easylifeMarketingAmount",
        "pusherTotalAmount",
        "easyLifeFrontAmount",
        "easyLifeFrontAmountPaid",
        "easyLifeAfterAmount",
        "easyLifeAfterAmountPaid",
        "easyLifeAwardsAmount",
        "easyLifeAwardsAmountPaid",
        "developerFrontBrokerage",
        "developerFrontActBrokerage",
        "developerAfterBrokerage",
        "developerAfterActBrokerage",
        "developerAwardsAmount",
        "developerAwardsActAmount",
        "brokerAfterAmountPaid",
        "brokerAwardsAmount",
        "frontBrokerageTotalPre",
        "backBrokerageTotalPre",
        "awardsAmountPre",
        "brokerageTotalPre"
      ];
      let timeFormatter = [
        "orderPaidTime",
        "paymentsReceivedTime",
        "awardsAmountPaidTime"
      ];

      let timeSliceFormatter = [
        "purchaseTime",
        "initialTime",
        "signTime",
        "purchaseCreateTime"
      ];
      if (moneyFormatter.includes(prop)) {
        return !val ? "0.00" : utils.formatMoney(val);
      }
      if (timeFormatter.includes(prop)) {
        return utils.getTimeString(val);
      }
      if (timeSliceFormatter.includes(prop)) {
        return utils.getTimeString(val).slice(0, 10);
      }
      if (prop === "customerPhone") {
        return utils.formatPhoneNumber(val);
      }
      if (prop === "brokerType") {
        if (val === 0) {
          return "网络推客";
        } else if (val == -1) {
          return "客户自然到访";
        } else {
          return "渠道";
        }
      }
      return val;
    },
    payTableFormatter(prop, val) {
      if (prop == "payOnThisTime") {
        return !val ? "0.00" : utils.formatMoney(val);
      }
      return val;
    },
    renderCommArray(row, prop, location, index) {
      //location记录下标和子对象
      //返回  brokerFrontBrokerageSettle[0]['brokerageSettleAmount']
      let idx = location[0];
      let nextProp = location[1];
      if (!row[prop].length) {
        return "——";
      }
      if (row[prop][idx] && row[prop][idx][nextProp]) {
        let val = row[prop][idx][nextProp];
        if (nextProp == "brokerageSettleAmount") {
          if (!val) return "0.00";
          return utils.formatMoney(val) || "——";
        }
        if (nextProp == "brokerageSettleTime") {
          return utils.getTimeString(val) || "——";
        }
      } else {
        if (nextProp == "brokerageSettleAmount") {
          return "——";
        }
        return "——";
      }
    },
    indexFun(index) {
      return !index ? "合计" : index;
    },
    jumpFlag(prop) {
      let leftOffset =
        this.$refs["out" + prop][0].parentNode.parentNode.offsetLeft - 500; //450为固定左列宽度
      this.thisOutProp = prop;
      this.$refs.table.bodyWrapper.scrollLeft = leftOffset;
    },
    selectable(row, idx) {
      //idx为0 禁用，0为合计行
      return !!idx;
    },
    selectChange(list) {
      //console.log(list);
    },
    searchList(pageNum) {
      let param = {
        ...this.model,
        pageSize: this.pageSize,
        pageNum: pageNum || this.pageNum
      };
      this.axios.post(api.getCashPoolList, param).then(res => {
        if (res.data.code == 200) {
          this.tableData = res.data.data.list || [];
          this.totalSize = res.data.data.total;
          if (this.tableData) {
            //记录第一个分佣数组
            let frontBrolker =
              this.tableData[0].brokerFrontBrokerageSettle || []; //前佣经纪人
            let frontCompany =
              this.tableData[0].companyFrontBrokerageSettle || []; //前佣经纪公司
            let afterBrolker =
              this.tableData[0].brokerAfterBrokerageSettle || []; //后佣经纪人
            let afterCompany =
              this.tableData[0].companyAfterBrokerageSettle || []; //后佣经纪公司
            let awardsSettle = this.tableData[0].brokerAwardsSettle || []; //经纪人奖励信息
            let frontAppendArray = []; //前佣需渲染
            let afterAppendArray = [];
            let awardAppendArray = [];
            frontBrolker.forEach((list, idx) => {
              frontAppendArray.push(
                {
                  label: `经纪人第${idx + 1}次结佣金额（元）`,
                  prop: "brokerFrontBrokerageSettle",
                  location: [idx, "brokerageSettleAmount"]
                },
                {
                  label: "结佣时间",
                  prop: "brokerFrontBrokerageSettle",
                  location: [idx, "brokerageSettleTime"]
                }
              );
            });
            frontCompany.forEach((list, idx) => {
              frontAppendArray.push(
                {
                  label: `经纪公司第${idx + 1}次结佣金额（元）`,
                  prop: "companyFrontBrokerageSettle",
                  location: [idx, "brokerageSettleAmount"]
                },
                {
                  label: "结佣时间",
                  prop: "companyFrontBrokerageSettle",
                  location: [idx, "brokerageSettleTime"]
                }
              );
            });
            afterBrolker.forEach((list, idx) => {
              afterAppendArray.push(
                {
                  label: `经纪人第${idx + 1}次结佣金额（元）`,
                  prop: "brokerAfterBrokerageSettle",
                  location: [idx, "brokerageSettleAmount"]
                },
                {
                  label: "结佣时间",
                  prop: "brokerAfterBrokerageSettle",
                  location: [idx, "brokerageSettleTime"]
                }
              );
            });
            afterCompany.forEach((list, idx) => {
              afterAppendArray.push(
                {
                  label: `经纪公司第${idx + 1}次结佣金额（元）`,
                  prop: "companyAfterBrokerageSettle",
                  location: [idx, "brokerageSettleAmount"]
                },
                {
                  label: "结佣时间",
                  prop: "companyAfterBrokerageSettle",
                  location: [idx, "brokerageSettleTime"]
                }
              );
            });
            awardsSettle.forEach((list, idx) => {
              awardAppendArray.push(
                {
                  label: `第${idx + 1}次结佣金额（元）`,
                  prop: "brokerAwardsSettle",
                  location: [idx, "brokerageSettleAmount"]
                },
                {
                  label: "结佣时间",
                  prop: "brokerAwardsSettle",
                  location: [idx, "brokerageSettleTime"]
                }
              );
            });

            this.tableTitleInfos[8].child = [
              { label: "应结前佣佣金（元）", prop: "brokerFrontAmount" },
              { label: "已结前佣佣金（元）", prop: "brokerFrontAmountPaid" },
              ...frontAppendArray
            ];
            this.tableTitleInfos[9].child = [
              { label: "应结后佣佣金（元）", prop: "brokerAfterAmount" },
              { label: "已结后佣佣金（元）", prop: "brokerAfterAmountPaid" },
              ...afterAppendArray
            ];
            this.tableTitleInfos[10].child = [
              { label: "应结经纪人奖励（元）", prop: "brokerAwardsAmount" },
              { label: "实结经纪人奖励（元）", prop: "brokerAwardsAmountPaid" },
              ...awardAppendArray
            ];
          }

          this.totalSize = res.data.data.total;
        }
      });
    },

    formMoneyValue(val) {
      if (val === 0) {
        return "0.00";
      } else if (!val) {
        return "——";
      } else {
        return utils.formatMoney(val);
      }
    },
    viewList(idx) {
      let { orderId, mergeId, brokerType } = this.tableData[idx];
      this.$router.push({
        path: "/efcapitalSummaryDetail",
        query: { orderId: orderId, mergeId: mergeId, brokerType: brokerType }
      });
    },
    viewCommInfo(id) {
      if (id) {
        window.open(`${api.viewCommInfo}customerFollowId=${id}`, true);
      }
    },
    //导出
    exportList() {
      let param = {
        ...this.model
      };
      this.axios({
        method: "post",
        url: api.exportCashPoolList,
        data: param,
        headers: {
          "content-type": "application/json; charset=utf-8",
          token: sessionStorage.getItem("cmsUser")
            ? JSON.parse(sessionStorage.getItem("cmsUser")).tokenId
            : ""
        },
        responseType: "blob"
      })
        .then(res => {
          this.downloadFile(res.data);
        })
        .catch(res => {
          //全局拦截器原因,返回参数为catch'
          this.downloadFile(res.data);
        });
    },
    downloadFile(data) {
      if (!data) {
        this.$message({
          message: "导出失败",
          type: "error"
        });
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      let fileName = `导出${utils.getTimeString(new Date())}.xls`;
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
      this.$message({
        message: "导出成功",
        type: "success"
      });
    },

    handleCurrentChange() {
      this.searchList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.searchList(1);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus" scoped>
.prop-tab {
  margin: 0 15px 15px 0;
}

.fixedBoxx {
  position: absolute;
  top: 25px;
  background: #fff;
  width: calc(100% - 50px);
}

.break-text {
  color: #409EFF;
  cursor: pointer;
}
</style>
<style lang="stylus">
.efCapitalSummary {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;

  .el-table__fixed {
    height: calc(100% - 16px) !important;
    box-shadow: 0px -5px 10px rgba(0, 0, 0, 0.12);
  }
}
</style>
